package com.quick.develop.flowable.framework.core;

import com.quick.develop.flowable.framework.enums.definition.BpmAddendumEnum;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * @author junyuan.liu
 * @description: 流程运行实例创建 设置相关信息 主要考虑自动启动子流程
 * 1、设置子流程的 BusinessKey 为主流程的BusinessKey
 * 2、设置子流程的 流程启动者  为主流程的-流程启动者
 * @date 2022/6/1 14:36
 */
@Component
@Slf4j
public class BpmProcessCreatedListener implements FlowableEventListener {

   /* @Resource
    protected IBpmExecutionService bpmExecutionService;*/

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onEvent(FlowableEvent flowableEvent) {
        ExecutionEntityImpl entity = (ExecutionEntityImpl) ((FlowableEntityEventImpl) flowableEvent).getEntity();
        //父节点调用活动信息
        ExecutionEntityImpl superExecution = entity.getSuperExecution();
        if (Objects.nonNull(superExecution)) {
            ExecutionEntityImpl callActivity = superExecution.getParent();
            //父流程信息
            ExecutionEntityImpl parent = callActivity.getParent();
            Optional.ofNullable(parent).ifPresent(p -> {
                entity.setBusinessKey(p.getBusinessKey());
                entity.setStartUserId(p.getStartUserId());
            });
//            superExecution.getParentId()  调用活动节点执行ID 可以通过此获得节点设置的局部参数
//             String subStartUser = bpmExecutionService.getSubStartUser(superExecution.getParentId());
            //主流程传到子流程的 创建的时候还获取不到全局参数 需要找主流程设置的人员
            /*if (StrUtil.isNotEmpty(subStartUser)) {
                entity.setStartUserId(subStartUser);
            }else {
                entity.setStartUserId(SecurityUtils.getUserCode());
            }*/
        } else {
            if (BpmAddendumEnum.isIgnore(entity.getProcessDefinitionKey())) {
                return;
            }
        }

    }

    @Override
    public boolean isFailOnException() {
        return true;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}
